<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/5
 * Time: 13:34
 */
namespace app\api\controller\followmanage;
use think\Controller;
use app\api\controller\common\ApiBase;
use Think\Db;
use app\api\model\Admin as AdminModel;

class Billing extends ApiBase
{
    protected $admin;
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('CompanyFollow');
    }

    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
     }

    /**
     * 私海列表
     * @param member_id,public_id,sale_id
     */
    public function index(){
        if (request()->isPost()) {
            $post = input('post.');
            $page = isset($post['page']) && $post['page'] != '' ? $post['page'] : 10;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : null;
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            $company_id = isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : null;
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $comRes=db($tabName)->where(['id'=>$company_id])->find();
            if(!$comRes){
                return json(['code'=>0,'msg'=>'展商数据错误']);
            }
            $basRes=db('company')->where(['id'=>$comRes['company_id1']])->find();
            $param=" and p.company_id=".$company_id." and p.exhibition_id=".$exhibition_id." and p.is_delete=0 ";
            $sql="SELECT p.*,c.company_name as zs_company_name FROM crm_billing as p ";
            $sql.=" LEFT JOIN crm_".$tabName." as c ON c.id=p.company_id";
            $sql.=" where 1=1 $param";
            $sql.=" order by p.id desc";
            $sql.=" limit ".($page-1)*$pageSize.",$pageSize";
            $list=Db::query($sql);
            $sql1=" select count(p.id) as count1 ";
            $sql1.=" from crm_billing as p where 1=1 $param ";
            $total1=Db::query($sql1);
            $total=$total1[0]['count1']; //st
            $dbMaxFill=db('billing')->where(['company_id'=>$company_id,'exhibition_id'=>$exhibition_id])->limit(1)->order("id desc")->select();
            $fillDetail=null;
            if(is_array($dbMaxFill) && count($dbMaxFill)>0){
                $fillDetail=$dbMaxFill[0];
            }else{
                $fillDetail=array(
                    'company_name'=>($comRes && $comRes['company_name'])?$comRes['company_name']:$basRes['company_name'],
                    'company_phone'=>($comRes && $comRes['mobile'])?$comRes['mobile']:$basRes['mobile'],
                    'receiving_phone'=>($comRes && $comRes['mobile_person'])?$comRes['mobile_person']:$basRes['mobile_person'],
                    'receiving_name'=>($comRes && $comRes['contact'])?$comRes['contact']:$basRes['contact'],
                    'company_address'=>($comRes && $comRes['company_address'])?$comRes['company_address']:$basRes['company_address'],
                );
            }
            return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total,'fill_detail'=>$fillDetail]]);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }



    /**
     * 添加开票记录
     */

     public function addOrEdit(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $admin = session('admin');
                $admin = AdminModel::get(['id' => $admin['id']]);
                $post = input('post.');
                if (empty($admin)) {
                    return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
                }
                $finance_id = isset($post['finance_id']) && $post['finance_id'] != '' ? $post['finance_id'] : 0;
                $financeRes=db('finance')->where(['id'=>$finance_id])->find();
                if(!$financeRes){
                    return json(array('code' => '0', 'msg' => '金额记录错误'));
                }
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
                $company_id = isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : null;
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
                $billing_type = isset($post['billing_type']) && $post['billing_type'] != '' ? $post['billing_type'] : 1;
                $tax_number = isset($post['tax_number']) && $post['tax_number'] != '' ? $post['tax_number'] : '';
                $bank_title = isset($post['bank_title']) && $post['bank_title'] != '' ? $post['bank_title'] : '';
                $bank_number = isset($post['bank_number']) && $post['bank_number'] != '' ? $post['bank_number'] : '';
                $company_phone = isset($post['company_phone']) && $post['company_phone'] != '' ? $post['company_phone'] : '';
                $company_name = isset($post['company_name']) && $post['company_name'] != '' ? $post['company_name'] : '';
                $company_address = isset($post['company_address']) && $post['company_address'] != '' ? $post['company_address'] : '';
                $billing_mode = isset($post['billing_mode']) && $post['billing_mode'] != '' ? $post['billing_mode'] : 1;
                $billing_money = isset($post['billing_money']) && $post['billing_money'] != '' ? $post['billing_money'] : '';
                $receiving_name = isset($post['receiving_name']) && $post['receiving_name'] != '' ? $post['receiving_name'] : '';
                $receiving_phone = isset($post['receiving_phone']) && $post['receiving_phone'] != '' ? $post['receiving_phone'] : '';
                $receiving_address = isset($post['receiving_address']) && $post['receiving_address'] != '' ? $post['receiving_address'] : '';
                if (!$exhibition_id) {
                    return json(array('code' => '0', 'msg' => '展会信息错误为空'));
                }
                $tabName=$this->getTabName($exhibition_id);
                $comRes=db($tabName)->where(['id'=>$company_id])->find();
                if(!$comRes){
                    return json(['code'=>0,'msg'=>'展商数据错误']);
                }

                $data['exhibition_id']=$exhibition_id;
                $data['company_id']=$company_id;
                $data['billing_type']=$billing_type;
                $data['tax_number']=$tax_number;
                $data['bank_title']=$bank_title;
                $data['bank_number']=$bank_number;
                $data['company_phone']=$company_phone;
                $data['company_address']=$company_address;
                $data['billing_mode']=$billing_mode;
                $data['billing_money']=$billing_money;
                $data['receiving_name']=$receiving_name;
                $data['company_name']=$company_name;
                $data['receiving_phone']=$receiving_phone;
                $data['receiving_address']=$receiving_address;
                $data['finance_id']=$finance_id;
                $data['create_time']=time();
                $data['update_time']=time();
                $data['member_id']=$admin['id'];
                $res='';
                if($id){
                    $search=db('billing')->where(['id'=>$id])->find();
                    if(!$search){
                        return json(array('code' => '0', 'msg' => '数据错误'));
                    }
                    if($search['billing_status'] == 2){
                        return json(array('code' => '0', 'msg' => '财务已开票，无法此操作'));
                    }
                    //先释放掉之前的财务状态再重新添加载物状态
                    $isokRes=db('finance')->where(['id'=>array('in',$search['finance_id']),'billing_status'=>array('neq',0)])->update(['billing_status'=>0]);
                    if(false==$isokRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '财务记录释放失败'));
                    }
                    $isokRes=db('finance')->where(['id'=>array('in',$finance_id),'billing_status'=>0])->update(['billing_status'=>1]);
                    if(false==$isokRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '财务记录添加失败'));
                    }

                    $res=db('billing')->where(['id'=>$id])->update($data);
                    if(false===$res){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }else{
                    $isokResLike=db('finance')->where(['id'=>array('in',$finance_id),'billing_status'=>0])->select();
                    if($isokResLike){
                        $isokRes=db('finance')->where(['id'=>array('in',$finance_id),'billing_status'=>0])->update(['billing_status'=>1]);
                        if(false==$isokRes){
                            Db::rollback();
                            return json(array('code' => '0', 'msg' => '操作失败'));
                        }
                    }
                    $res=db('billing')->insert($data);
                    if(false===$res){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }

                    if($receiving_name) {
                        $baseData['mail_person'] = $receiving_name;
                        $baseData['mail_mobile'] = $receiving_phone;
                        $baseData['mail_address'] = $receiving_address;
                        db('company')->where(['id' => $comRes['company_id1']])->update($baseData);
                    }
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '操作成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
     }


    /**
     * 撤回开票记录
     */

    public function del(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $finance_id = isset($post['finance_id']) && $post['finance_id'] != '' ? $post['finance_id'] : 0;
                $search=db('billing')->where(['id'=>$id])->find();
                if(!$search){
                    return json(array('code' => '0', 'msg' => '数据错误'));
                }

                if($search['billing_status'] == 2){
                    return json(array('code' => '0', 'msg' => '财务已开票，无法此操作'));
                }

                $financeRes=db('finance')->where(['id'=>array('in',$finance_id)])->select();
                if(count($financeRes)==0){
                    return json(array('code' => '0', 'msg' => '金额记录错误'));
                }
                $isOkfind=db('finance')->where(['id'=>array('in',$finance_id),'billing_status'=>array('gt',0)])->select();
                if(count($isOkfind)>0){
                    $isokRes=db('finance')->where(['id'=>array('in',$finance_id),'billing_status'=>array('gt',0)])->update(['billing_status'=>0]);
                    if(false==$isokRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }

                $res=db('billing')->where(['id'=>$id])->update(['is_delete'=>1]);
                if(!$res){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }

                Db::commit();
                return json(array('code' => '1', 'msg' => '操作成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 付款记录
     */

    public function billingList(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
            $company_id=isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : 0;
            $status=isset($post['status']) && $post['status'] != '' ? $post['status'] : 1;
            $parms=' is_delete=0 ';
            if($status == 1){
                $parms=" billing_status=0";
            }else if($status==2){
                $parms=" billing_status<2";
            }
            if(!$exhibition_id){
                return json(array('code' => '0', 'msg' => '展会信息错误为空'));
            }
            if(!$company_id){
                return json(array('code' => '0', 'msg' => '展商信息错误为空'));
            }
            $sql="SELECT * FROM crm_finance ";
            $sql.=" WHERE contract_id IN (SELECT id FROM crm_contract WHERE id_zhui=".$exhibition_id." AND id_zs=".$company_id." AND is_delete=0 AND s_status=1) ";
            $sql.=" AND status>1 and ".$parms;
            $list=Db::query($sql);
            return json(array('code' => '1', 'msg' => '操作成功','data'=>$list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function setStatus(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $search=db('billing')->where(['id'=>$id])->find();
                if(!$search){
                    return json(array('code' => '0', 'msg' => '数据错误'));
                }
                if($search['billing_status'] == 1){
                    return json(array('code' => '0', 'msg' => '已申请，请勿重复操作'));
                }
                if($search['billing_status'] == 2){
                    return json(array('code' => '0', 'msg' => '已开票，无法此操作'));
                }
                $res=db('billing')->where(['id'=>$id])->update(['billing_status'=>1,'submit_time'=>time()]);
                if(false==$res){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                $finList=db('finance')->where(['id'=>array('in',$search['finance_id']),'billing_status'=>1])->select();
                if($finList){
                    $finRes=db('finance')->where(['id'=>array('in',$search['finance_id']),'billing_status'=>1])->update(['billing_status'=>2]);
                    if(false==$finRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '操作成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

}
